package com.ss.android.common.thread;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;

import com.ss.android.common.util.StringUtils;

public class AbstractThread extends Thread{
	private final int TIMEOUT=20000;
	protected final Handler mHandler;
	private String url=null;
	
	public AbstractThread(Handler handler){
		this.mHandler=handler;
	}
	
	protected String executeGet() throws ClientProtocolException,IOException{
		if(StringUtils.isEmpty(getUrl())){
			HttpResponse response;
			BasicHttpParams params=new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClientParams.setRedirecting(params, true);
			DefaultHttpClient httpClient=new DefaultHttpClient(params);
			response=httpClient.execute(new HttpGet(getUrl()));
			if(response.getStatusLine().getStatusCode()==200){
				return EntityUtils.toString(response.getEntity(),"UTF-8");
			}
		}
		return null;
	}
	
	protected String executePost(List<BasicNameValuePair> list)
			throws ClientProtocolException,IOException{
		if(StringUtils.isEmpty(getUrl())){
			HttpResponse response;
			HttpPost httpPost=new HttpPost(getUrl());
			httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
			BasicHttpParams params=new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClientParams.setRedirecting(params, true);
			DefaultHttpClient httpClient=new DefaultHttpClient(params);
			response=httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==200){
				return EntityUtils.toString(response.getEntity());
			}
		}
		return null;
	}
	
	protected String getUrl(){
		return this.url;
	}
	
	protected boolean isSuccessful(String str) throws JSONException{
		return (str!=null)&&("success".equals(new JSONObject(str).getString("message")));
	}
	
	protected void setUrl(String str){
		this.url=str;
	}
}
